/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.task.evaluation;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import edu.cmu.lti.sepia.infra.run.RunXmlFacade;
import edu.cmu.lti.sepia.infra.run.model.AnswerCandidate;
import edu.cmu.lti.sepia.infra.run.model.SelectionResult;
import edu.cmu.lti.sepia.infra.run.model.SelectionResultSet;

/**
 * Given a set of submissions, create one xml file that goes into a pool
 * @author hideki
 *
 */
public class QAEvaluationSetup {

  public static void createPool(File[] inputs, File output) throws Exception {
    SelectionResultSet pool = new SelectionResultSet();
    for (File input : inputs) {
      FileInputStream is = new FileInputStream(input);
      SelectionResultSet answers = RunXmlFacade.deserializeSelectionResultSet(is);

      for ( String topicId : answers.keySet() ) {
        List<String> history = new ArrayList<String>();
        SelectionResult poolResult = pool.get(topicId);
        SelectionResult systemResult = answers.get(topicId);
        if (poolResult==null) {
          poolResult = new SelectionResult();
        } else {
          for ( AnswerCandidate ac : poolResult ) {
            history.add(ac.getText());
          }
        }
        for ( AnswerCandidate ac : systemResult ) {
          if (!history.contains(ac.getText())) {
            poolResult.add(ac);
            history.add(ac.getText());
          }
        }
        pool.put(topicId, poolResult);
      }
      is.close();
    }
    System.out.println("Pool created for "+pool.size()+" topics");
    String poolXML = RunXmlFacade.serializeSelectionResultSet(pool);
//    System.out.println(poolXML);
    FileOutputStream fos = new FileOutputStream(output);
    OutputStreamWriter out = new OutputStreamWriter(fos);
    BufferedWriter bw = new BufferedWriter(out);
    bw.write(poolXML);
    bw.close();
    out.close();
    fos.close();
  }
  
  public static void main(String[] args) throws Exception {
    File dir = new File("C:\\Users\\hideki\\Desktop\\aclia\\cclqa pooling\\");
    createPool(new File(dir,"cs").listFiles(), new File(dir,"cs-pool.xml"));
  }
  
}
